import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { UserDocument } from '@/user/schemas/user.schema';
import { HydratedDocument, Types } from 'mongoose';
import { Channel, ChannelSchema } from './channel.schema';
import { v4 as uuidv4 } from 'uuid';

export type WorkDocument = HydratedDocument<Work>;
interface IworkContent {
  [key: string]: any;
}
@Schema({
  timestamps: true,
  toJSON: {
    transform(doc, ret) {
      delete ret.password;
      delete ret.__v;
      delete ret._id;
      if (ret.createdAt) {
        ret.createdAt = new Date(ret.createdAt).toLocaleString('zh-CN', {
          timeZone: 'Asia/Shanghai',
        });
      }
      if (ret.updatedAt) {
        ret.updatedAt = new Date(ret.updatedAt).toLocaleString('zh-CN', {
          timeZone: 'Asia/Shanghai',
        });
      }
      return ret;
    },
  },
})
export class Work {
  @Prop({ required: true, unique: true, default: uuidv4 })
  uuid: string;

  @Prop({ required: true })
  title: string;

  // 副标题，描述
  @Prop({ required: true })
  desc?: string;

  //   内容数据 { components: [], props: {} }
  @Prop({ type: Object })
  content?: IworkContent;

  @Prop()
  author?: string;

  @Prop()
  coverImg?: string;

  //   状态：0-删除，1-未发布，2-发布，3-管理员强制下线
  @Prop({ required: true, enum: [0, 1, 2, 3] })
  status: number;

  //   是否模板
  @Prop({ default: false })
  isTemplate: boolean;

  //   是否热门
  @Prop({ default: false })
  isHot: boolean;

  //  被复制的次数
  @Prop({ default: 0 })
  copiedCount: number;

  @Prop({ default: false })
  isPublic: boolean;

  //   作者的 ID，链接到用户表
  @Prop({ type: Types.ObjectId, ref: 'User', required: true })
  user: UserDocument['_id'];

  @Prop()
  latestPublishAt: Date;

  @Prop({ type: [ChannelSchema], default: [] })
  channels: Channel[];
}
export const WorkSchema = SchemaFactory.createForClass(Work);
